const UniPayService = require('./unipay.js')
const uniPay = require('uni-pay');
/**
 * 支付宝支付处理
 */
module.exports = class AlipayService extends UniPayService {
	constructor(ctx) {
		super(ctx)
		this.type = "alipay";
		this.payname = "支付宝";
	}

	async prepay(userInfo) {
		return {
			key: this.type,
			icon: "icon_pay_alipay",
			color: "#55aaff",
			name: this.payname,
			confirm: false
		}
	}

	async _beforeCreateOrder(options, config, order, userInfo) {
		if (order.subAppId) {
			//支付宝服务商模式
			const info = await this.service.alipay.app.getInfoByAppIdCache(order.subAppId)
			if (info) {
				options.appAuthToken = info.app_auth_token;
				//设置卖家ID，否则报卖家无权限
				options.sellerId = info.user_id
			}
		}
	}
	/**
	 * 验证参数是否合法
	 * @param {Object} config
	 * @param {Object} event
	 * @param {Object} next
	 */
	async verify(config, event, next) {
		let uniPayIns = uniPay[config["uniPay"]](config);
		//如果验证失败，会抛出异常，成功才能进入下面
		let res = await uniPayIns.verifyPaymentNotify(event);
		console.log("uniPayIns.verifyPaymentNotify", res)
		res.type = this.type;
		//处理各类订单支付完成之后的回调
		await next(res);
		//返回成功字符串
		return this.returnNotifyData()
	}
	async transfers(data, platform, desc) {
		return {
			code: 0,
			message: "线下手动处理"
		}
	}
	/**
	 * 返回给支付宝服务器
	 */
	returnNotifyData() {
		return {
			header: "text/plain",
			result: "success"
		}
	}

	getOpenid(userInfo) {
		if (userInfo.ali_openid) {
			return userInfo.ali_openid;
		}
	}
}
